<script setup lang="ts">
import * as THREE from "three";
import { ref, onMounted, type Ref, h } from "vue";
import gsap from "gsap";
import { Room } from "./utils/Room";
import { PositionSprite } from "./utils/PositionSprite";

// 初始化场景
const scene = new THREE.Scene();
// 创建相机
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);

// 相机放入到场景中
camera.position.set(0, 0, 0.01);

// 创建渲染器
const renderer = new THREE.WebGLRenderer();
// 设置渲染器大小
renderer.setSize(window.innerWidth, window.innerHeight);

const container = ref<HTMLElement | null>(null);

const render = () => {
  renderer.render(scene, camera);
  requestAnimationFrame(render);
};

window.addEventListener("resize", () => {
  // 更新相机的宽高比
  camera.aspect = window.innerWidth / window.innerHeight;
  // 更新相机的投影矩阵
  camera.updateProjectionMatrix();
  // 更新渲染器的大小
  renderer.setSize(window.innerWidth, window.innerHeight);
});

onMounted(() => { 
  if (container.value) {
    container.value.appendChild(renderer.domElement);
    render();

    let isMouseDown = false;
    container.value.addEventListener(
      "mousedown",
      () => {
        isMouseDown = true;
      },
      false
    );
    container.value.addEventListener(
      "mouseup",
      () => {
        isMouseDown = false;
      },
      false
    );
    container.value.addEventListener(
      "mouseout",
      () => {
        isMouseDown = false;
      },
      false
    );

    container.value.addEventListener("mousemove", (event) => {
      if (isMouseDown) {
        camera.rotation.x += event.movementY * 0.01;
        camera.rotation.y += event.movementX * 0.01;
        camera.rotation.order = "YXZ";
      }
    });

    new Room("客厅", "living", "./images/livingRoom/", scene);

    const balconyPosition = new THREE.Vector3(0, 0, -10);
    new Room("阳台", "balcony", "./images/balcony/", scene, balconyPosition);

    // 阳台位置标识
    const balconySprite = new PositionSprite(
      "阳台",
      new THREE.Vector3(0, 0, -4),
      scene,
      camera
    )
    balconySprite.onClick(() => { 
      gsap.to(camera.position, {
        duration: 1,
        x: 0,
        y: 0,
        z: -10,
      });
    })

    // 回到客厅位置标识
    const balconyBackSprite = new PositionSprite(
      "客厅",
      new THREE.Vector3(1, 0, -6),
      scene,
      camera
    )
    balconyBackSprite.onClick(() => { 
      gsap.to(camera.position, {
        duration: 1,
        x: 0,
        y: 0,
        z: 0,
      });
    })
  }
})

</script>

<template>
  <div class="container" ref="container"></div>
</template>

<style lang="scss">
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.container{
  width: 100vw;
  height: 100vh;
}
</style>
